package com.gitbl.webchat.roomnode;


import com.gitbl.webchat.utils.ArgumentsHelper;
import groovyjarjarcommonscli.ParseException;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.log4j.Logger;

import java.util.Properties;
import java.util.concurrent.TimeUnit;

public class Application {

    private final Logger logger=Logger.getLogger(this.getClass());

    //定时任务，注入到主循环，避免多线程
    void startTimer(NioEventLoopGroup boss){
        boss.schedule(new Runnable() {
            @Override
            public void run() {
                try {
                    //更新节点及房间信息
                    RoomsNode.instance().update();
                }catch (Exception ex){

                }
                startTimer(boss);
            }
        },5, TimeUnit.SECONDS);
    }

    private void run(){

        logger.info("正在启动websocket服务器");
        NioEventLoopGroup boss=new NioEventLoopGroup(1);
        startTimer(boss);
        int port = Integer.parseInt(NodeDetails.addr.split(":")[1]);

        try {
            ServerBootstrap bootstrap=new ServerBootstrap();
            bootstrap.group(boss,boss);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.childHandler(new NioWebSocketChannelInitializer());
            Channel channel = bootstrap.bind(port).sync().channel();
            logger.info("webSocket服务器启动成功："+channel);
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
            logger.info("运行出错："+e);
        }finally {
            boss.shutdownGracefully();

            logger.info("websocket服务器已关闭");
        }
    }

    public static void main(String[] args) throws ParseException {
        Properties pps = ArgumentsHelper.parseProperties(args, "use value for given property(property=value) \neg: -Daddr=192.168.10.121:8081"+
                "\\\n-Dcache.hosts=127.0.0.1:6379","webchat-roomnode-1.0-SNAPSHOT.jar" );

        if(pps==null){
            return;
        }
        for (Object p:pps.keySet()
             ) {
            if(p.toString().equals("addr")){
                NodeDetails.addr = pps.getProperty(p.toString());
            }else if(p.toString().equals("cache.hosts")){
                System.setProperty(p.toString(),pps.getProperty(p.toString()));
            }
        }

        RoomsNode.init();
        new Application().run();
    }
}
